package com.millstein.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.millstein.enums.order.ProductOrderStateEnum;
import com.millstein.enums.product.LockStateEnum;
import com.millstein.feign.OrderFeignService;
import com.millstein.model.ProductDO;
import com.millstein.model.ProductMessage;
import com.millstein.model.ProductTaskDO;
import com.millstein.mapper.ProductTaskMapper;
import com.millstein.service.ProductService;
import com.millstein.service.ProductTaskService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.millstein.util.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author millstein
 * @since 2021-09-19
 */
@Service
@Slf4j
public class ProductTaskServiceImpl extends ServiceImpl<ProductTaskMapper, ProductTaskDO> implements ProductTaskService {

    @Autowired
    private OrderFeignService orderFeignService;

    @Autowired
    private ProductService productService;

    /**
     * 解锁库存，并返回是否需要重新投递
     *
     * @param productMessage 消息的内容
     * @return
     */
    @Override
    @Transactional
    public boolean doReleaseProduct(ProductMessage productMessage) {
        String outTradeNo = productMessage.getOutTradeNo();
        // 1.查询任务列表
        ProductTaskDO dbTask = this.getById(productMessage.getTaskId());

        if (dbTask == null) {
            log.warn("解锁库存的记录不存在：{}", productMessage);
            return false;
        }

        if (!dbTask.getLockState().equals(LockStateEnum.LOCK.name())) {
            log.warn("解锁库存的记录状态不是LOCK，不进行后续处理：{}", productMessage);
            return false;
        }

        // 2.查询订单的状态
        JsonData result = orderFeignService.getProductOrderStateByOutTradeNo(outTradeNo);

        if (result.getCode() == 0) {
            String state = (String) result.getData();

            if (state.equals(ProductOrderStateEnum.NEW.name())) {
                log.warn("订单记录为NEW，需要进行重新投递：{}", productMessage);
                return true;
            }

            if (state.equals(ProductOrderStateEnum.PAY.name())) {
                log.info("订单记录为已支付，需要将锁定库存任务的状态修改为FINISH");
                dbTask.setLockState(LockStateEnum.FINISH.name());
                this.updateById(dbTask);
                return false;
            }
        }

        log.warn("订单不存在，获取已被取消，修改锁定记录的状态是CANCEL，并恢复锁定前的库存：{}", productMessage);
        dbTask.setLockState(LockStateEnum.CANCEL.name());
        this.updateById(dbTask);

        ProductDO dbProduct = productService.getById(dbTask.getProductId());
        dbProduct.setLockStock(dbProduct.getLockStock() - dbTask.getBuyNum());
        productService.updateById(dbProduct);
        return false;
    }
}
